package net.zjitc.springboot_mybatisplus.contrller;

import net.zjitc.springboot_mybatisplus.dao.BookDao;
import net.zjitc.springboot_mybatisplus.domain.Book;
import net.zjitc.springboot_mybatisplus.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class BookController {
    @Autowired
    private BookService bookService;

    @Autowired
    private BookDao bookDao;

    @RequestMapping("/tests")
    public String test(Model model) {
        model.addAttribute("message", bookService.getById(1));
        return "book";
    }

    @RequestMapping("/books")
    public String book(Model model) {
        List<Book> books=bookService.list();
        System.out.println("打印书籍信息"+books.size());
        books.forEach(System.out::println);
        model.addAttribute("books", books);
        return "book_list";
    }

    @RequestMapping("/book-form")
    public String addBook(Model model) {
        model.addAttribute("book", new Book());
        return "book-form";
    }

    @RequestMapping("/submit-book")
    public String submitBook(Model model, @ModelAttribute Book book) {
        bookDao.insert(book);
        model.addAttribute("book", book);
        return "book-result";
    }

    @RequestMapping("/view-book")
    public String searchBook(Model model,@RequestParam Integer id) {
        Book book=bookDao.selectById(id);
        if(book==null){
            return "error";
        }
        model.addAttribute("book", book);
        return "book-detail";
    }
    @RequestMapping("/book/edit/{id}")
    public String editForm(Model model,@PathVariable Integer id) {
        Book book=bookDao.selectById(id);
        if(book==null){
            return "error";
        }
        model.addAttribute("book", book);
        return "book-edit";
    }
    @RequestMapping("/book/update")
    public String updateBook(Model model,@ModelAttribute Book book) {
        bookDao.updateById(book);
        model.addAttribute("book", book);
        return "book-detail";
    }

    @RequestMapping("/delete-book")
    public String deleteBook(@RequestParam("id") Integer id) {
        boolean deleted=bookService.removeById(id);
        if(deleted){
            return "redirect:/book-form";
        }else {
            return "redirect:/error";
        }

    }

}
